<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Streamed Q&A</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        input[type="text"] {
            width: 300px;
            padding: 10px;
            margin-right: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 10px 20px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        #answer {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            min-height: 100px;
        }

        #error {
            color: red;
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <h1>流式问答系统</h1>
    <input type="text" id="question" placeholder="请输入你的问题">
    <button id="askButton">提问</button>
    <div id="answer"></div>
    <div id="error"></div>

    <script>
        function askQuestion() {
            const question = document.getElementById('question').value;
            const errorDiv = document.getElementById('error');
            const answerDiv = document.getElementById('answer');

            // 输入验证
            if (question.trim() === '') {
                errorDiv.textContent = '请输入问题';
                return;
            }

            errorDiv.textContent = '';
            answerDiv.textContent = '';

            const eventSource = new EventSource(`/ask?question=${encodeURIComponent(question)}`);

            eventSource.onmessage = function (event) {
                answerDiv.textContent += event.data;
            };

            eventSource.onerror = function (error) {
                errorDiv.textContent = '发生错误，请稍后再试';
                console.error('EventSource failed:', error);
                eventSource.close();
            };
        }

        // 使用事件监听器绑定按钮的点击事件
        const askButton = document.getElementById('askButton');
        askButton.addEventListener('click', askQuestion);
    </script>
</body>

</html>
